package com.waypolice.manager.shiro;

import com.waypolice.common.utils.MD5Util;
import com.waypolice.manager.service.UpmsApiService;
import com.waypolice.pojo.*;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * 自定义Realm,进行数据认证和授权操作
 * (Shiro的安全数据桥)
 * @author wr
 *
 */
public class RealmUtils extends AuthorizingRealm{

	@Autowired
	private UpmsApiService upmsApiService;

	//登陆认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

		String username = (String) token.getPrincipal();
		String password = new String((char[]) token.getCredentials());

		/*//登陆唯一性的另外一种处理方式
		DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
		DefaultWebSessionManager sessionManager = (DefaultWebSessionManager)securityManager.getSessionManager();
		Collection<Session> sessions = sessionManager.getSessionDAO().getActiveSessions();//获取当前已登录的用户session列表
		for(Session session:sessions){
			//清除该用户以前登录时保存的session
			if(username.equals(String.valueOf(session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)))) {
				sessionManager.getSessionDAO().delete(session);
			}
		}*/

		// 查询用户信息
		UpmsUser upmsUser = upmsApiService.selectUpmsUserByUsername(username);

		if (null == upmsUser) {
			throw new UnknownAccountException();
		}
		if (!upmsUser.getPassword().equals(MD5Util.md5(password + upmsUser.getSalt()))) {
			throw new IncorrectCredentialsException();
		}
		if (upmsUser.getLocked() == 1) {
			throw new LockedAccountException();
		}

		return new SimpleAuthenticationInfo(username, password, getName());
	}
	
	//鉴权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = (String) principals.getPrimaryPrincipal();
        UpmsUser upmsUser = upmsApiService.selectUpmsUserByUsername(username);
		//UpmsUser upmsUser = (UpmsUser) principals.getPrimaryPrincipal();

		// 当前用户所有角色
		List<UpmsRole> upmsRoles = upmsApiService.selectUpmsRoleByUpmsUserId(upmsUser.getUserId());
		Set<String> roles = new HashSet<>();
		for (UpmsRole upmsRole : upmsRoles) {
			if (org.apache.commons.lang.StringUtils.isNotBlank(upmsRole.getName())) {
				roles.add(upmsRole.getName());
			}
		}

		// 当前用户所有权限
		List<UpmsPermission> upmsPermissions = upmsApiService.selectUpmsPermissionByUpmsUserId(upmsUser.getUserId());
		Set<String> permissions = new HashSet<>();
		for (UpmsPermission upmsPermission : upmsPermissions) {
			if (org.apache.commons.lang.StringUtils.isNotBlank(upmsPermission.getPermissionValue())) {
				permissions.add(upmsPermission.getPermissionValue());
			}
		}

		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		simpleAuthorizationInfo.setStringPermissions(permissions);
		simpleAuthorizationInfo.setRoles(roles);
		return simpleAuthorizationInfo;
	}
}
